<template>
  <div class="page_padding">
    <MyNavBar @goback="goback" title="办公用品申请单" />
    <div class="add_con">
      <div class="con_box">
        <div class="box_head">
          <div class="head_title">{{ detailInfo.title }}</div>
          <div class="head_info">
            <div class="info_org">部门名称：{{ detailInfo.orgName }}</div>
            <div class="info_num">总人数：{{ detailInfo.headCount }}人</div>
          </div>
        </div>
        <div class="box_info">
          <van-collapse v-model="activeName" accordion :border="false">
            <div class="info_box">
              <van-collapse-item
                :border="false"
                class="box_collapse"
                :name="index + 1"
                v-for="(item, index) in formData.tableData"
                :key="index"
                :disabled="formData.tableData.length === 1"
                :class="{ no_collapse: formData.tableData.length == 1 }">
                <template #title>
                  <div class="coll_title">
                    <div class="title_left">
                      <span class="title_tips">{{ getDoubleNum(index + 1) }}</span>
                      <div class="title_info" v-if="activeName != index + 1">
                        <span>{{ item.name }}</span>
                        <span>{{ item.applyNumber }}</span>
                        <span>{{ item.specs }}</span>
                      </div>
                    </div>
                    <div
                      class="title_r"
                      v-if="
                        formData.tableData.length > 1 &&
                        isEdit &&
                        (isOtherRole || isNormalRole || isOrgRole) &&
                        approveNode !== '2'
                      ">
                      <span @click.stop="cancelinfo(index)" class="">
                        <van-icon name="delete-o" />
                        删除
                      </span>
                    </div>
                    <!-- <div
                      class="title_r"
                      v-if="
                        formData.tableData.length > 1 &&
                        isEdit &&
                        isApplyRole &&
                        (item.createBy === userId || !item.createBy)
                      ">
                      <span @click.stop="cancelinfo(index)" class="">
                        <van-icon name="delete-o" />
                        删除
                      </span>
                    </div> -->
                  </div>
                </template>
                <div class="info_input_data">
                  <div class="info_text">
                    <div class="info_text_title">物品名称</div>
                    <div class="info_text_r" @click="chooseThing(item, index)">
                      <van-cell is-link :class="{ placeholder: !item.name }">
                        <template #default>
                          {{ item.name || '请选择物品' }}
                        </template>
                      </van-cell>
                    </div>
                  </div>
                  <div class="info_text pad_left_board">
                    <div class="info_text_title">规格</div>
                    <div class="info_text_r">
                      <van-cell :class="{ placeholder: !item.specs }">
                        <template #default>
                          {{ item.specs || '请选择物品' }}
                        </template>
                      </van-cell>
                    </div>
                  </div>
                </div>
                <div class="info_input_data">
                  <div class="info_text">
                    <div class="info_text_title">申请数量</div>
                    <div class="info_input_r">
                      <van-field
                        class="info_fied_input"
                        maxlength="4"
                        v-model="item.applyNumber"
                        label=""
                        type="number"
                        placeholder="请输入"
                        :readonly="!isEdit || (isApplyRole && approveNode === '2')"
                        @blur="inputBlur($event, index)" />
                    </div>
                  </div>
                  <div class="info_text" v-if="isApplyRole && approveNode === '2'">
                    <div class="info_text_title">实际领取数量</div>
                    <div class="info_input_r">
                      <van-field
                        class="info_fied_input"
                        maxlength="4"
                        v-model="item.realityNumber"
                        label=""
                        type="number"
                        placeholder="请输入"
                        :readonly="!isEdit"
                        @blur="inputBlurs($event, index)" />
                    </div>
                  </div>
                </div>
                <div class="info_input_data remark">
                  <div class="info_text">
                    <div class="info_text_title">备注</div>
                    <div class="info_input_r">
                      <van-field
                        class="info_fied_input"
                        v-model="item.remark"
                        label=""
                        :placeholder="
                          isEdit && (isNormalRole || isOtherRole || isOrgRole) && approveNode !== '2' ? '请输入' : '无'
                        "
                        type="textarea"
                        autosize
                        rows="1"
                        :readonly="!isEdit || (isApplyRole && approveNode === '2')" />
                    </div>
                  </div>
                </div>
              </van-collapse-item>
              <div
                class="now_info_add"
                v-if="isEdit && (isNormalRole || isOtherRole || isOrgRole) && approveNode !== '2'">
                <div class="info_add-one" @click="addRowsinfo">
                  <van-icon name="add-o" class="add_icon" />
                  <span>添加</span>
                </div>
              </div>
            </div>
          </van-collapse>
        </div>
        <div class="box_annex">
          <div class="list_text_title">
            <span class="text">附件：</span>
          </div>
          <ImgUpload
            :albumList.sync="formData.enclosureList"
            :entry="isEdit && (isNormalRole || isOtherRole || isOrgRole) && detailInfo.flowNode !== '2'"
            v-if="formData.enclosureList.length > 0 || (isEdit && (isNormalRole || isOtherRole || isOrgRole))" />
          <p class="entry_cont" v-else>无</p>
        </div>
      </div>
      <van-collapse class="check_main" v-model="activeName2" accordion v-if="detailInfo.isSave === '1'">
        <van-collapse-item name="0">
          <template #title>
            <div class="type_title_bold">审批流程</div>
          </template>
          <logisticsSteps :approveFlow="approveFlow" />
        </van-collapse-item>
      </van-collapse>
    </div>
    <div class="check_btn" v-if="detailInfo.isSave === '0' && (isNormalRole || isOtherRole || isOrgRole)">
      <van-button size="small" v-if="!isEdit" @click="edit">编 辑</van-button>
      <van-button size="small" v-if="isEdit" @click="saveData('0')">保 存</van-button>
      <van-button size="small" type="info" @click="saveData('1')">提 交</van-button>
      <van-button size="small" type="danger" @click="delForm">删 除</van-button>
    </div>
    <div
      class="check_btn"
      v-else-if="isOrgRole && detailInfo.status === '0' && queryInfo.firstType !== '0' && approveNode === '1'">
      <van-button size="small" v-if="!isEdit" @click="goEdit">编 辑</van-button>
      <van-button size="small" v-if="isEdit" @click="saveData('1')">保 存</van-button>
      <van-button size="small" type="info" @click="approvalData('1')">通 过</van-button>
      <van-button size="small" type="danger" @click="approvalData('2')">不通过</van-button>
    </div>
    <div class="check_btn" v-else-if="isApplyRole && detailInfo.status === '0' && approveNode === '2'">
      <van-button size="small" type="info" @click="goEdit" v-if="!isEdit">修 改</van-button>
      <van-button size="small" type="info" @click="saveData('1')" v-else>保 存</van-button>
    </div>
    <van-action-sheet
      v-model="actionShow"
      close-on-click-action
      :round="false"
      @select="onSelect"
      :actions="chooseList"
      max-height="70%"></van-action-sheet>
  </div>
</template>

<script>
import MyNavBar from '@com/MyNavBar'
import { getLogicticsInfoDetail, delLogicticsInfo, updateLogicticsInfo, approveForm } from '@api/api-dailyManage.js'
import logisticsSteps from './components/logisticsSteps.vue'
import moment from 'moment'
import ImgUpload from '@com/ImgUpload'
import { mapGetters } from 'vuex'
import { getDoubleNum } from '@common/utility'
export default {
  name: 'logisticsDetail',
  components: {
    ImgUpload,
    MyNavBar,
    logisticsSteps,
  },
  props: {},
  data() {
    return {
      getDoubleNum,
      // type,1审核，2退回，3知会，4系统消息,5是自己
      moment: moment,
      formData: {
        radio: '1',
        enclosureList: [],
        tableData: [],
      },
      userInfo: JSON.parse(localStorage.userInfo),
      activeName: 1,
      finishList: [
        { value: '1', name: '已完成' },
        { value: '0', name: '进行中' },
      ],
      taskList: [], // 所属类型
      activeName2: '', // 审批流程
      approveFlow: {},
      detailInfo: {},
      actionShow: false,
      chooseList: [],
      thingList: [],
      activeInfo: {},
      activeIndex: '',
      queryInfo: this.$route.query,
      isEdit: false,
      userId: localStorage.userId,
      tabList: [],
      approveNode: '', // 1:负责人审批,2:最终审批
    }
  },
  computed: {
    ...mapGetters('role', ['isOtherRole', 'isNormalRole', 'isOrgRole', 'isApplyRole']),
  },
  watch: {
    formData: {
      handler(news) {
        if (this.isApplyRole && this.approveNode === '2') {
          return
        }
        const arr = this.thingList.filter(itemA => {
          return news.tableData.every(itemB => {
            return itemB.typeId !== itemA.typeId
          })
        })
        // if (this.isEditFlag) {
        //   arr.unshift(this.activeEditInfo)
        // }
        this.chooseList = arr
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getLogicticsInfoDetail()
  },
  mounted() {
    this.approveFlow = {
      id: this.queryInfo.id,
      processInstanceId: this.queryInfo.processInstanceId,
    }
  },
  methods: {
    goback() {
      this.$router.go(-1)
    },
    cancelinfo(index) {
      this.formData.tableData.splice(index, 1)
      this.activeName = index === 0 ? 1 : index
    },
    chooseThing(item, index) {
      if (
        !this.isEdit ||
        (this.isApplyRole && item.createBy && this.userId !== item.createBy && this.approveNode === '2')
      ) {
        return
      }
      this.activeIndex = index
      if (item.name) {
        this.activeInfo = item
        this.chooseList.unshift(item)
      } else {
        this.activeInfo = {}
      }
      this.actionShow = true
    },
    addRowsinfo() {
      // let obj = this.formData.tableData[this.formData.tableData.length - 1]
      // if (!obj.name || !Number(obj.applyNumber)) {
      //   return this.$toast('您有暂未完成的内容，请先完成或者删除')
      // }
      this.formData.tableData.push({
        name: '',
        typeId: '',
        defaultQty: '',
        applyNumber: '',
        realityNumber: 0,
        specs: '',
        isEdit: true,
      })
      this.activeName = this.formData.tableData.length
    },
    getLogicticsInfoDetail() {
      getLogicticsInfoDetail({
        id: this.$route.query.id,
      }).then(res => {
        if (res.code === 0) {
          this.detailInfo = res.data
          if (this.detailInfo.currentNodeName) {
            this.approveNode = this.detailInfo.currentNodeName.indexOf('负责人') !== -1 ? '1' : '2'
          } else {
            this.approveNode = ''
          }
          this.thingList = JSON.parse(JSON.stringify(this.detailInfo.itemTypeList)) || []
          this.formData.tableData = this.detailInfo.detailList
          this.formData.enclosureList = this.detailInfo.enclosureList
        }
      })
    },
    onSelect(val) {
      const item = val
      const index = this.activeIndex
      this.$set(this.formData.tableData[index], 'detailId', item.detailId || '')
      this.$set(this.formData.tableData[index], 'typeId', item.typeId)
      this.$set(this.formData.tableData[index], 'name', item.name)
      this.$set(this.formData.tableData[index], 'specs', item.specs)
      this.$set(this.formData.tableData[index], 'defaultQty', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'applyNumber', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'realityNumber', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'remark', item.remark)
    },
    edit() {
      this.isEdit = true
    },
    saveData(type) {
      let dataList = []
      if (this.isNormalRole || this.isOtherRole || this.isOrgRole) {
        if (type === '0') {
          const arr = this.formData.tableData.filter(item => {
            return !item.name
          })
          if (arr.length === this.formData.tableData.length) {
            return this.$toast.fail('请至少选择一种办公用品')
          }
          dataList = this.formData.tableData.filter(item => {
            return item.name
          })
        } else {
          const arr = this.formData.tableData.filter(item => {
            return !item.name || !Number(item.applyNumber)
          })
          if (arr.length > 0) {
            return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
          }
          dataList = this.formData.tableData
        }
      }
      if (this.isApplyRole && this.approveNode === '2') {
        const arr1 = this.formData.tableData.filter(item => {
          return (this.userId === item.createBy || !item.createBy) && (!item.name || !Number(item.applyNumber))
        })
        if (arr1.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
        const arr = this.formData.tableData.filter(item => {
          return item.applyNumber === ''
        })
        if (arr.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
        dataList = this.formData.tableData
      }
      if (this.isApplyRole && this.approveNode === '2') {
        const arr = this.formData.tableData.filter(item => {
          return item.realityNumber === ''
        })
        if (arr.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
        dataList = this.formData.tableData
      }
      this.isEdit = false
      dataList.forEach((item, index) => {
        this.$set(item, 'sort', index + 1)
      })
      const param = {
        applyType: this.detailInfo.applyType,
        enclosureList: this.formData.enclosureList,
        headCount: this.detailInfo.headCount,
        itemTypeList: dataList,
        orgName: this.detailInfo.orgName,
        orgId: this.detailInfo.orgId,
        year: this.detailInfo.year,
        month: this.detailInfo.month,
        title: this.detailInfo.title,
        isSave: type,
        id: this.detailInfo.id,
      }
      updateLogicticsInfo(param).then(res => {
        if (res.code === 0) {
          if (type === '0') {
            this.$toast.success('暂存成功')
            setTimeout(() => {
              this.getLogicticsInfoDetail()
            }, 500)
          } else {
            if (this.firstType === '0') {
              this.$toast.success('提交成功')
              setTimeout(() => {
                this.$router.go(-1)
              }, 500)
            } else {
              this.$toast.success('保存成功')
              setTimeout(() => {
                this.getLogicticsInfoDetail()
              }, 500)
            }
          }
        }
      })
    },
    delForm() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '确定删除该领用单吗？',
        })
        .then(() => {
          delLogicticsInfo({
            id: this.queryInfo.id,
          })
            .then(res => {
              if (res.code === 0) {
                this.$toast.success('删除成功')
                setTimeout(() => {
                  this.$router.go(-1)
                }, 500)
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    goEdit() {
      this.isEdit = true
    },
    approvalData(type) {
      if (this.isOrgRole) {
        const arr = this.formData.tableData.filter(item => {
          return !item.name || !Number(item.applyNumber)
        })
        if (arr.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
      }
      if (this.isApplyRole && this.approveNode === '2') {
        const arr1 = this.formData.tableData.filter(item => {
          return (this.userId === item.createBy || !item.createBy) && (!item.name || !Number(item.applyNumber))
        })
        if (arr1.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
        const arr = this.formData.tableData.filter(item => {
          return item.applyNumber === ''
        })
        if (arr.length > 0) {
          return this.$toast.fail('您有尚未填写完整的内容，请先完成或者取消。')
        }
      }
      // let obj = this.formData.tableData[this.formData.tableData.length - 1]
      // if (!obj.name || obj.applyNumber === '') {
      //   return this.$toast('您有暂未完成的内容，请先完成或者删除')
      // }
      this.formData.tableData.forEach((item, index) => {
        this.$set(item, 'sort', index + 1)
      })
      if (this.isEdit) {
        const param = {
          applyType: this.detailInfo.applyType,
          enclosureList: this.formData.enclosureList,
          headCount: this.detailInfo.headCount,
          itemTypeList: this.formData.tableData,
          orgName: this.detailInfo.orgName,
          orgId: this.detailInfo.orgId,
          year: this.detailInfo.year,
          month: this.detailInfo.month,
          title: this.detailInfo.title,
          isSave: type,
          id: this.detailInfo.id,
        }
        updateLogicticsInfo(param).then(res => {
          if (res.code === 0) {
            const params = {
              content: '',
              id: this.queryInfo.id,
              processInstanceId: this.queryInfo.processInstanceId,
              status: type,
              taskId: this.queryInfo.taskId,
            }
            approveForm(params).then(res => {
              if (res.code === 0) {
                this.$toast.success('审批成功')
                setTimeout(() => {
                  this.$router.go(-1)
                }, 500)
              }
            })
          }
        })
      } else {
        this.isEdit = false
        const param = {
          content: '',
          id: this.queryInfo.id,
          processInstanceId: this.queryInfo.processInstanceId,
          status: type,
          taskId: this.queryInfo.taskId,
        }
        approveForm(param).then(res => {
          if (res.code === 0) {
            this.$toast.success('审批成功')
            setTimeout(() => {
              this.$router.go(-1)
            }, 500)
          }
        })
      }
    },
    goSure() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '请确认当月物品已发放完毕，确定后不可修改。',
        })
        .then(() => {
          // approveBatch().then(res => {
          //   if (res.code === 0) {
          //     this.$toast.success('确定成功')
          //     setTimeout(() => {
          //       this.$router.go(-1)
          //     }, 500)
          //   }
          // })
        })
        .catch(() => {})
    },
    inputBlur(e, index) {
      this.formData.tableData[index].applyNumber = Number(e.target.value)
      this.formData.tableData[index].realityNumber = Number(e.target.value)
    },
    inputBlurs(e, index) {
      this.formData.tableData[index].realityNumber = Number(e.target.value)
    },
  },
}
</script>

<style lang="scss" scoped>
.add_con {
  padding: 7px 12px 60px;
  background-color: #f5f5f5;
  font-size: 13px;
  color: #333333;
  width: 100%;
  overflow-x: hidden;
  min-height: 100%;
  .con_box {
    width: 100%;
    background-color: #ffffff;
    padding: 10px 10px;
    box-shadow: 0 0 10px 0 rgba(4, 0, 0, 0.15);
    border-radius: 5px;
    .box_head {
      .head_title {
        border-bottom: 1px solid #efefef;
        padding: 10px 0;
        text-align: center;
        font-weight: 600;
        font-size: 16px;
      }
      .head_info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px solid #efefef;
      }
    }
    .box_info {
      .info_box {
        /deep/ .van-collapse-item {
          .van-collapse-item__content {
            padding: 0;
          }
        }
        .no_collapse {
          /deep/ .van-collapse-item__title {
            .van-icon-arrow {
              display: none;
            }
          }
        }
        .box_collapse {
          padding: 0 10px;
          border-bottom: 2px solid #f0f0f0;
          margin-bottom: 7px;
          /deep/.van-cell {
            padding: 10px 0;
          }
        }
        .coll_title {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .title_left {
          font-weight: 800;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          flex: 1;
          width: 0;
          display: flex;
          .title_tips {
            background-image: linear-gradient(#ffffff 50%, #e5d2b4);
            color: #333333;
          }
          .title_info {
            padding-left: 17px;
            color: #333333;
            span {
              margin-right: 14px;
            }
          }
        }
        .title_r {
          display: flex;
          align-items: center;
          color: #4b79bb;
          font-size: 12px;
          span {
            display: flex;
            align-items: center;
            padding-right: 7px;
          }
        }
        .info_input_data {
          display: flex;
          .info_text {
            // width: 50%;
            flex: 1;
            border-top: 1px solid #f0f0f0;
          }
          .pad_left_board {
            width: 75px;
            max-width: 75px;
            padding-left: 5px;
          }
        }
        .remark {
          .info_text {
            .info_input_r {
              padding-left: 15px;
              .info_fied_input {
                height: auto !important;
              }
            }
          }
        }

        .info_text {
          display: flex;
          align-items: center;
          padding: 5px 0;
          .info_text_title {
            color: #333333;
            font-size: 12px;
          }
          .info_text_r {
            flex: 1;
            text-align: right;
            span {
              margin-right: 8px;
            }
            .van-cell {
              justify-content: flex-end;
              padding: 0;
              align-items: center;
              .van-cell__value {
                text-align: right;
                font-size: 12px;
              }
              /deep/ .van-icon {
                display: flex;
                align-items: center;
              }
            }
            .placeholder {
              .van-cell__value--alone {
                color: #c8c9cc;
              }
            }
            /deep/.van-radio-group {
              .van-radio {
                margin-left: 20px;
                font-size: 12px;
                .van-radio__icon {
                  font-size: 15px;
                }
                .van-radio__icon--checked .van-icon {
                  background-color: #5f7290;
                  border-color: #5f7290;
                }
              }
            }
            .van-dropdown-menu {
              display: flex;
              align-items: center;
              justify-content: flex-end;
              position: relative;
            }
            /deep/ .van-dropdown-menu__title::after {
              display: none;
            }
            /deep/.van-dropdown-menu__item {
              justify-content: flex-end;
            }
            /deep/ .van-dropdown-menu__bar {
              height: 30px;
              box-shadow: none;
            }
            /deep/ .van-dropdown-item {
              // position: absolute;
              height: 500px;
              width: 100%;
              .van-dropdown-item__content {
                max-height: 50%;
              }
            }
            /deep/ .van-dropdown-menu__title {
              font-size: 12px;
              // color: #999999;
            }
            .is_select {
              background-color: #8ba018;
              padding: 3px 5px;
            }
          }
          .info_input_r {
            flex: 1;
            .info_fied_input {
              padding: 0 5px;
              width: 100%;
              height: 30px;
              line-height: 30px;
              font-size: 12px;
              resize: none;
            }
            /deep/.van-field__control {
              // color: #999999;
              text-align: right;
            }
            /deep/.van-icon {
              font-size: 12px;
            }
          }
        }
        .now_info_add {
          padding-bottom: 10px;
          .info_add-one {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #86642c;
            font-size: 15px;
            padding: 10px 0;
            border: 1px solid #86642c;
            border-radius: 5px;
            font-weight: 600;
            span {
              margin-left: 7px;
            }
          }
        }
      }
    }
    .box_annex {
      // 标题
      .list_text_title {
        font-size: 15px;
        font-weight: 800;
        color: #333;
        margin-bottom: 20px;
        .text {
          background-image: linear-gradient(#ffffff 50%, #e5d2b4);
        }
      }
      .entry_cont {
        padding-left: 10px;
      }
    }
  }
  .check_main {
    background-color: #ffffff;
    padding: 5px;
    box-shadow: 0 0 10px 0 rgba(4, 0, 0, 0.15);
    margin-top: 10px;
    border-radius: 5px;
    .type_title_bold {
      font-size: 14px;
      color: #333333;
      font-weight: 600;
    }
  }
}
.check_btn {
  margin-top: 10px;
  background-color: #ffffff;
  padding: 5px 15px;
  box-shadow: 0 0 10px 0 rgba(4, 0, 0, 0.15);
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 50px;
  /deep/.van-button {
    height: 32px;
  }
}
/deep/.van-action-sheet {
  padding-bottom: 10px;
  max-height: 60%;
  .van-action-sheet__content {
    .van-action-sheet__item {
      border: none !important;
    }
  }
}
</style>
